<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;

class Category extends Model
{
    //
    use SoftDeletes;
    use ModelTree, AdminBuilder;
    
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    
        $this->setParentColumn('parent_id');
        $this->setOrderColumn('listorder');
        $this->setTitleColumn('name');
    }
    
    public static function menu($arr = array())
    {
        if($arr)
        {
            $all = Category::whereIn('id', $arr)->orderBy('listorder', 'asc')->orderBy('id', 'asc')->get();
            
        }else{
            $all = Category::orderBy('listorder', 'asc')->orderBy('id', 'asc')->get();
            
        }
        foreach ($all as $row) {
            if($row->parent_id == 0) {
                $menu[$row->id] = $row->toArray();
            }
        }
        foreach ($all as $row) {
            if($row->parent_id > 0) {
                $menu[$row->parent_id]['child'][] = $row->toArray();
            }
    
        }
        return $menu;
    
    }
}
